package cn.yoaket.util;

import cn.yoaket.exception.ContextException;

import java.lang.reflect.Constructor;


/**
 * @author Alex
 */
public class BeanGenerate {

    private BeanGenerate(){

    }
    public static Object generate(BeanDefinition def) throws ContextException {
        Class<?> c;
        Constructor<?> con;
        Object obj;
        try{
           c =  Class.forName(def.className);
            con = c.getConstructor();
            obj = con.newInstance();
        }catch (Exception e){
            throw new ContextException(ContextException.Type.INSTANCE_ERROR);
        }
        var fields = c.getDeclaredFields();

        var fieldMap = def.getFields();
        for(var field: fields){
            field.setAccessible(true);
            if(fieldMap.containsKey(field.getName())){
                try {
                    String value = fieldMap.get(field.getName());
                    field.set(obj,value);
                }catch (Exception e){
                    throw new ContextException(ContextException.Type.ASSIGNMENT_ERROR);
                }
            }
        }
        return  obj;
    }
}


